package com.my.screenadapter.net.retrofit;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Looper;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.daimajia.numberprogressbar.NumberProgressBar;
import com.google.gson.Gson;

import com.ihsanbal.logging.Level;
import com.ihsanbal.logging.LoggingInterceptor;
import com.ljd.retrofit.progress.DownloadProgressHandler;
import com.ljd.retrofit.progress.ProgressHelper;
import com.my.screenadapter.BuildConfig;
import com.my.screenadapter.R;
import com.my.screenadapter.net.User;
import com.my.screenadapter.net.myConvert.MyGsonConverterFactory;
import com.my.screenadapter.net.myConvert.TestUser;

import org.apache.log4j.Logger;
import org.litepal.crud.DataSupport;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.internal.platform.Platform;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ${张英杰} on 2017/3/14.
 * <p>
 * http://square.github.io/retrofit/
 * 张鸿洋：
 * http://blog.csdn.net/lmj623565791/article/details/51304204
 * <p>
 * bugly 分享 Retrofit
 * https://juejin.im/entry/57514c3d1532bc00647d32c7
 * <p>
 * 进度条
 * http://blog.csdn.net/ljd2038/article/details/51189334
 */

public class RetrofitActivity extends AppCompatActivity {
    Gson gson;
    final String LoginUrl = "http://139.129.194.173:9002/api/sys/app/";
    @BindView(R.id.down)
    Button down;
    @BindView(R.id.username)
    EditText username;
    @BindView(R.id.pwd)
    EditText pwd;
    @BindView(R.id.up)
    Button up;
    @BindView(R.id.show)
    Button show;
    @BindView(R.id.tv_show)
    TextView tvShow;
    @BindView(R.id.Field)
    Button Field;
    @BindView(R.id.FieldMap)
    Button FieldMap;
    @BindView(R.id.Part)
    Button Part;
    @BindView(R.id.PartMap)
    Button PartMap;
    @BindView(R.id.RequestBodyConverter)
    Button RequestBodyConverter;
    @BindView(R.id.downProgress)
    Button downProgress;
    @BindView(R.id.tvProgress)
    TextView tvProgress;
    @BindView(R.id.progressbar)
    NumberProgressBar progressbar;
    private static final String TAG = "RetrofitActivity";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
        ButterKnife.bind(this);
        gson = new Gson();
        final EditText username = (EditText) findViewById(R.id.username);
        final EditText pwd = (EditText) findViewById(R.id.pwd);
        final TextView tvshow = (TextView) findViewById(R.id.tv_show);
        findViewById(R.id.show).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User first = DataSupport.findFirst(User.class);
                tvshow.setText(gson.toJson(first));
            }
        });


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        final ClientService service = retrofit.create(ClientService.class);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Call<String> stringCall = service.hostGithub("hello");
                stringCall.enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        Log.i(TAG, "onResponse: string github Thread:"+Thread.currentThread().getName());
                        if (response != null && response.body() != null) {
                            Log.i(TAG, "onResponse: "+response.body().toString());
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        Log.e(TAG, "onFailure: ",t );
                    }
                });
            }
        }).start();
        Call<User> abc = service.login("abc");
        abc.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                Log.i(TAG, "onResponse: githubthread:"+Thread.currentThread().getName());
                if (response != null && response.body() != null) {
                    Log.i(TAG, "onResponse: "+response.body().toString());
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Log.e(TAG, "onFailure: ",t );
            }
        });


        findViewById(R.id.up).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(LoginUrl)//这里的baseUrl加上之前@POST("mobileLogin/submit.html")定义的参数形成完整的请求地址；
//                        //增加返回值为String的支持
//                        .addConverterFactory(ScalarsConverterFactory.create())
                        //增加返回值为Gson的支持(以实体类返回)
                        .addConverterFactory(GsonConverterFactory.create())
//                        //增加返回值为Oservable<T>的支持
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .build();
                ClientService clientService = retrofit.create(ClientService.class);//这里采用的是Java的动态代理模式
                Call<User> call = clientService.login(username.getText().toString().trim() + "," + pwd.getText().toString().trim());//传入我们请求的键值对的值
//                利用得到的Call对象，然后我们就发出网络请求了：
                call.enqueue(new Callback<User>() {
                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {
                        if (response != null) {
                            boolean save = false;
                            int update = -1;
                            List<User> all = DataSupport.findAll(User.class);
                            if (all.size() > 0) {
                                update = response.body().update(all.get(0).getId());
                            } else {
                                save = response.body().save();
                            }
                            Log.e("成功===", "保存:" + save + " Update=" + update + " return:" + new Gson().toJson(response.body()));
                        }
                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable t) {
                        Log.e("失败===", "失败" + call.toString() + t.toString());
                    }
                });
            }
        });
        Button viewById = (Button) findViewById(R.id.down);
        viewById.setText("loginQueryMap");
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("lifecircle", "123");
                map.put("tt", "456");
                Call<User> userCall = new Retrofit.Builder()
                        .baseUrl(LoginUrl)
                        //增加返回值为Gson的支持(以实体类返回)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()
                        .create(ClientService.class)
                        .loginQueryMap(map);
                Request request = userCall.request();
                //查看 request 具体信息。
                Log.i(TAG, "onClick: RequestBody---> "+gson.toJson(request));
                        userCall.enqueue(new Callback<User>() {
                            @Override
                            public void onResponse(Call<User> call, Response<User> response) {
                                Log.i("loginQueryMap===ss", response.body().toString());
                            }

                            @Override
                            public void onFailure(Call<User> call, Throwable t) {
                                Log.i("loginQueryMap===ff", t.toString());
                            }
                        });
            }
        });
    }

    @OnClick(R.id.downProgress)
    public void setDownProgress() {
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setProgressNumberFormat("%1d KB/%2d KB");
        dialog.setTitle("下载");
        dialog.setMessage("正在下载，请稍后...");
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setCancelable(false);
        dialog.show();
        progressbar.setVisibility(View.VISIBLE);
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
//                .baseUrl("http://msoftdl.360.cn");
                .baseUrl("http://zj.cdn.beeboxes.com");

        OkHttpClient.Builder builder = ProgressHelper.addProgress(null);

        //add log record
        if (BuildConfig.DEBUG) {
        //打印网络请求日志
            LoggingInterceptor httpLoggingInterceptor = new LoggingInterceptor.Builder()
                    .loggable(BuildConfig.DEBUG)
                    .setLevel(Level.BASIC)
                    .log(Platform.INFO)
                    .request("Request")
                    .response("Response")
                    .build();
            builder.addInterceptor(httpLoggingInterceptor);
        }

        ClientService clientService = retrofitBuilder
                .client(builder.build())
                .build()
                .create(ClientService.class);

        ProgressHelper.setProgressHandler(new DownloadProgressHandler() {
            @Override
            protected void onProgress(long bytesRead, long contentLength, boolean done) {
                Log.e("是否在主线程中运行", String.valueOf(Looper.getMainLooper() == Looper.myLooper()));
                Log.e("onProgress", String.format("%d%% done\n", (100 * bytesRead) / contentLength));
                Log.e("done", "--->" + String.valueOf(done));
                //设置进度条
                int bl = (int) (contentLength / 100);
                int intcurrent = (int) (bytesRead / bl);
                progressbar.setMax(100);
                progressbar.setProgress(intcurrent);
                dialog.setMax((int) (contentLength / 1024));
                dialog.setProgress((int) (bytesRead / 1024));
                if (done) {
                    dialog.dismiss();
                }
                if (done){
                    progressbar.setVisibility(View.GONE);
                }
            }
        });

        clientService
//                .downloadProgress()
                .downloadProgress2()
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            InputStream is = response.body().byteStream();
                            File downLoad = getExternalFilesDir("DownLoad");
                            File file = new File(downLoad, "12345AAA.apk");
                            FileOutputStream fos = new FileOutputStream(file);
                            BufferedInputStream bis = new BufferedInputStream(is);
                            byte[] buffer = new byte[1024];
                            int len;
                            while ((len = bis.read(buffer)) != -1) {
                                fos.write(buffer, 0, len);
                                fos.flush();
                            }
                            fos.close();
                            bis.close();
                            is.close();
                            Log.i("sss===", "保存陈宫");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        if (progressbar.getVisibility()==View.VISIBLE){
                            progressbar.setVisibility(View.GONE);
                        }
                        if (dialog.isShowing()){
                           dialog.dismiss();
                        }
                        Log.e("onFailure===", t.toString());
                        t.printStackTrace();
                    }
                });
    }

    @OnClick(R.id.btn_moveurl)
    public void postMoveUrl(){
        RetrofitUtil.getRetrofitStr()
                .postMoveURL(username.getText().toString().trim())
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {

                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {

                    }
                });
        RetrofitUtil.getRetrofitStr()
                .postMoveURL_TWO(username.getText().toString().trim())
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {

                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {

                    }
                });
        RetrofitUtil.getRetrofitStr()
                .postMoveURL_THree(username.getText().toString().trim())
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {

                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {

                    }
                });
    }


    @OnClick(R.id.btn_change_base_url)
    public void ChangeBaseUrl(){
        RetrofitUtil.getRetrofitStr().changeBaseUrl("https://www.baidu.com")
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {

                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {

                    }
                });
    }

    Logger logger = Logger.getLogger(RetrofitActivity.class);
    public void testMutiConvertFactory(View view) {
        RetrofitUtil.getRetrofitStr().multiConvertFactory("http://172.16.20.204:8080/oips/ad/gainAppIdAndAdslotId?sn=C1030451802072")
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        logger.info("response==="+response.body());
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        logger.info("Throwable==="+t.getMessage());
                    }
                });
        RetrofitUtil.getRetrofitStr().multiConvertFactoryGson("http://172.16.20.204:8080/oips/ad/gainAppIdAndAdslotId?sn=C1030451802072")
                .enqueue(new Callback<MultiConvertFactoryBean>() {
                    @Override
                    public void onResponse(Call<MultiConvertFactoryBean> call, Response<MultiConvertFactoryBean> response) {
                        logger.info("response  MultiConvertFactoryBean==="+response.body());
                        logger.info("response  MultiConvertFactoryBean==="+response.body().getAppId());
                    }

                    @Override
                    public void onFailure(Call<MultiConvertFactoryBean> call, Throwable t) {
                        logger.info("Throwable  MultiConvertFactoryBean==="+t.getMessage());
                    }
                });
    }


    public void myConvertFacory(View view) {
        //charies 代理返回测试
        String myUrl = "http://www.baidu.cn/mytestconvertfactory";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.baidu.cn")
                .addConverterFactory(MyGsonConverterFactory.create())
                .build();
        ClientService clientService = retrofit.create(ClientService.class);
        clientService.testMyConvertFactoryForResponseIllegal(myUrl)
                .enqueue(new Callback<TestUser>() {
                    @Override
                    public void onResponse(Call<TestUser> call, Response<TestUser> response) {
                        if (response.body() != null) {
                            Log.i(TAG, "onResponse: " + response.body().toString());
                        }
                    }

                    @Override
                    public void onFailure(Call<TestUser> call, Throwable t) {
                        Log.e(TAG, "onFailure: ",t);
                    }
                });
    }
}
